using Abc.Core.Entities;

using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.FriendlyException;

using Mapster;

using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.Extensions.Caching.Memory;

using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Abc.Core
{
    /// <summary>
    /// 用户管理接口
    /// </summary>
    public class HtAdminManager : IHtAdminManager, IScoped
    {
        /// <summary>
        /// 用户仓储
        /// </summary>
        private readonly IRepository<User> _userRepository;

        /// <summary>
        /// HttpContext 访问器
        /// </summary>
        private readonly IHttpContextAccessor _httpContextAccessor;

        /// <summary>
        /// 缓存
        /// </summary>
        private readonly IMemoryCache _memoryCache;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="httpContextAccessor"></param>
        /// <param name="userRepository"></param>
        /// <param name="memoryCache"></param>
        public HtAdminManager(IHttpContextAccessor httpContextAccessor
            , IRepository<User> userRepository
            , IMemoryCache memoryCache)
        {
            _httpContextAccessor = httpContextAccessor;
            _userRepository = userRepository;
            _memoryCache = memoryCache;
        }

        /// <summary>
        /// 获取用户 Id
        /// </summary>
        public int UserId {
            get {

                if (_httpContextAccessor.HttpContext.User != null && _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
                {
                    if (_httpContextAccessor.HttpContext.User.Claims.Any(o => o.Type == ClaimTypes.Sid))
                    {
                        var v = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Sid).Value;
                        return v.To<int>();
                    }
                }
                return 0;
            }
        }
        /// <summary>
        /// 获取用户 Id
        /// </summary>
        public string UserAccount {
            get {
                return _httpContextAccessor.HttpContext.User.Identity.Name;
            }
        }

        /// <summary>
        /// 获取用户 Id
        /// </summary>
        public string UserNick {
            get {
                if (_httpContextAccessor.HttpContext.User != null && _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
                {
                    if (_httpContextAccessor.HttpContext.User.Claims.Any(o => o.Type == ClaimTypes.Name))
                    {
                        var v = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name).Value;
                        return v.To<string>();
                    }
                }
                return UserAccount;
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        public User User {
            get {
                if (UserId > 0)
                {
                    return _userRepository.FirstOrDefault(o => o.Id == UserId).Adapt(User);
                }
                else
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 检查用户是否有效
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="tracking"></param>
        /// <returns></returns>
        public async Task<User> CheckUserAsync(int userId, bool tracking = true)
        {
            // 查询用户是否存在
            var user = await _userRepository.FirstOrDefaultAsync(u => u.Id == userId, tracking);
            return user ?? throw Oops.Oh(SystemErrorCodes.u1002);
        }

        ///// <summary>
        ///// 查询用户权限
        ///// </summary>
        ///// <param name="userId"></param>
        ///// <returns></returns>
        //public async Task<List<Security>> GetSecuritiesAsync(int userId)
        //{
        //    //return await _memoryCache.GetOrCreateAsync($"{userId}_securities", async (_) =>
        //    //{
        //    //    return await _userRepository.Include(u => u.Roles, false)
        //    //                                    .ThenInclude(u => u.Securities)
        //    //                                .Where(u => u.Id == userId)
        //    //                                .SelectMany(u => u.Roles
        //    //                                    .SelectMany(u => u.Securities))
        //    //                                .ToListAsync();
        //    //});

        //    return new List<Security>();
        //}
    }

    /// <summary>
    /// 用户管理接口
    /// </summary>
    public interface IHtAdminManager
    {
        /// <summary>
        /// 获取用户 Id
        /// </summary>
        int UserId { get; }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        User User { get; }

        /// <summary>
        /// 检查用户是否有效
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="tracking"></param>
        /// <returns></returns>
        Task<User> CheckUserAsync(int userId, bool tracking = true);

        ///// <summary>
        ///// 查询用户权限
        ///// </summary>
        ///// <param name="userId"></param>
        ///// <returns></returns>
        //Task<List<Security>> GetSecuritiesAsync(int userId);
    }
}